﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SmartSpace.UI.Silverlight.Dynamic.DynamicRef;
using SmartSpace.UI.Silverlight.Dynamic.Util;
using SmartSpace.UI.Silverlight.Dynamic.Controls;
using SmartSpace.UI.Silverlight.Dynamic.Windows;

namespace SmartSpace.UI.Silverlight.Dynamic
{
    public partial class DetailTemplateView : AppView
    {
        private Guid _workflowId { get; set; }
        private Guid _activityId { get; set; }
        public Guid _dataId { get; set; }
        private List<IAsyncControl> _asyncControls{get;set;}
        private List<PMFDataControl> _fieldControls { get; set; }

        private ViewMetadata _viewMetadata;
        private DataInstance _dataInstance;

        /// <summary>
        /// 数据是否有被更改过
        /// </summary>
        private bool _hasModified;

        public DetailTemplateView()
            :base(new Guid("{9EA20E99-2D0F-41EB-8A2F-93653A185C4D}"), "创建视图")
        {
            InitializeComponent();
        }

        public DetailTemplateView(Guid workflowId, Guid activityId, Guid dataId)
            :this()
        {
            _workflowId = workflowId;
            _activityId = activityId;
            _dataId = dataId;
        }

        protected override void OnExtendShown()
        {
            if (IsFirstDisplay)
            {
                if (_workflowId == default(Guid))
                {
                    _workflowId = new Guid(Arguments["workflowid"].ToString());
                    _activityId = new Guid(Arguments["activityid"].ToString());
                }

                _asyncControls = new List<IAsyncControl>();
                _fieldControls = new List<PMFDataControl>();
                LoadMetadata();
            }
        }

        #region load data
        private void LoadMetadata()
        {
            m_busy.IsBusy = true;

            DynamicWebServiceSoapClient client = DynamicModule.CreateProxy();
            client.GetViewMetadataCompleted += new EventHandler<GetViewMetadataCompletedEventArgs>(client_GetViewMetadataCompleted);
            client.GetViewMetadataAsync(_workflowId, _activityId, 1, 0, this.Authentication.UserID);
        }

        void client_GetViewMetadataCompleted(object sender, GetViewMetadataCompletedEventArgs e)
        {
            if (e.Error != null)
            {
            }
            else if (!e.Result.IsSuccess)
            {
            }
            else
            {
                _viewMetadata = e.Result.Data;
                DynamicWebServiceSoapClient client = DynamicModule.CreateProxy();
                client.GetDataCompleted += new EventHandler<GetDataCompletedEventArgs>(client_GetDataCompleted);
                client.GetDataAsync(_workflowId, _activityId, _dataId);
            }
        }

        void client_GetDataCompleted(object sender, GetDataCompletedEventArgs e)
        {
            if (e.Error != null)
            {
            }
            else if (!e.Result.IsSuccess)
            {
            }
            else
            {
                _dataInstance = e.Result.Data;
                _dataId = _dataInstance.Id;

                ViewLayoutUtil.BuildUI(this.Authentication.UserID,
                       _viewMetadata,
                       this.m_detailView,
                       _asyncControls,
                       _fieldControls);
                this.DataContext = _dataInstance;

                ResetToolbar(_viewMetadata, _dataInstance);

                if (_dataId != default(Guid))
                {
                    // 获取可以执行的操作
                    DynamicWebServiceSoapClient client = DynamicModule.CreateProxy();
                    client.GetEventsCompleted += new EventHandler<GetEventsCompletedEventArgs>(client_GetEventsCompleted);
                    client.GetEventsAsync(_workflowId, _activityId, _dataInstance.Id);
                }
                else
                {
                    m_busy.IsBusy = false;
                }
            }
        }

        #endregion

        private void _ctlBtnSubmit_Click(object sender, RoutedEventArgs e)
        {
            WorkflowEvent @event = _ctlListOperate.SelectedItem as WorkflowEvent;
            if (@event != null)
            {
                if (@event.Type == "sendtouser")
                {
                    SelectReceiverWindow window = new SelectReceiverWindow(_workflowId, _activityId, @event);
                    window.Closed += new EventHandler(OnSelectReceiverWindow_Closed);
                    window.Show();
                }
                else if (@event.Type == "issuedtodepartment")
                {
                    SmartSpace.UI.Silverlight.Dynamic.Windows.SelectOrgWindow window = new Windows.SelectOrgWindow(_workflowId, _activityId, @event);
                    window.Show();
                }
                else if (@event.Type == "sendtoself" || @event.Type == "sendtoprevious")
                {
                    ArrayOfGuid receivers = new ArrayOfGuid();
                    // 提交数据
                    DynamicWebServiceSoapClient client = DynamicModule.CreateProxy();
                    client.DriveCompleted += new EventHandler<DriveCompletedEventArgs>(client_DriveCompleted);
                    client.DriveAsync(_workflowId, _activityId, @event.Id, _dataInstance.Id, receivers);
                }
            }
        }

        void OnSelectReceiverWindow_Closed(object sender, EventArgs e)
        {
            SelectReceiverWindow window = sender as SelectReceiverWindow;
            if (window.DialogResult == true)
            {
                ArrayOfGuid receivers = new ArrayOfGuid();
                for (int i = 0; i < window.ReceiverIdList.Count; i++)
                {
                    receivers.Add(window.ReceiverIdList[i]);
                }

                // 提交数据
                DynamicWebServiceSoapClient client = DynamicModule.CreateProxy();
                client.DriveCompleted += new EventHandler<DriveCompletedEventArgs>(client_DriveCompleted);
                client.DriveAsync(_workflowId, _activityId, window.WorkflowEvent.Id, _dataInstance.Id, receivers);
            }
        }

        void client_DriveCompleted(object sender, DriveCompletedEventArgs e)
        {
            m_busy.IsBusy = false;

            if (e.Error != null)
            {
            }
            else if (!e.Result.IsSuccess)
            {
            }
            else
            {
                this.Submit();
                MessageService.ShowMessage("保存成功!");
            }
        }

        private void _ctlBtnSave_Click(object sender, RoutedEventArgs e)
        {
            m_busy.IsBusy = true;
            foreach (var item in this._fieldControls)
            {
                item.UpdateSource();
            }

            DynamicWebServiceSoapClient client = DynamicModule.CreateProxy();
            client.SaveDataCompleted += new EventHandler<SaveDataCompletedEventArgs>(client_SaveDataCompleted);
            client.SaveDataAsync(_workflowId, _activityId, _dataInstance);
        }

        void client_SaveDataCompleted(object sender, SaveDataCompletedEventArgs e)
        {
            if (e.Error != null)
            {
            }
            else if (!e.Result.IsSuccess)
            {
            }
            else
            {
                _hasModified = true;
                _dataInstance = e.Result.Data;
                _dataId = _dataInstance.Id;
                this.DataContext = _dataInstance;
                ResetToolbar(_viewMetadata, _dataInstance);
                MessageService.ShowMessage("保存成功!");

                // 获取可以执行的操作
                DynamicWebServiceSoapClient client = DynamicModule.CreateProxy();
                client.GetEventsCompleted += new EventHandler<GetEventsCompletedEventArgs>(client_GetEventsCompleted);
                client.GetEventsAsync(_workflowId, _activityId, _dataInstance.Id);
            }
        }

        void client_GetEventsCompleted(object sender, GetEventsCompletedEventArgs e)
        {
            if (e.Error != null)
            {
            }
            else if (!e.Result.IsSuccess)
            {
            }
            else
            {
                if (e.Result.Data.Count == 0)
                {
                    m_operatePanel.Visibility = System.Windows.Visibility.Collapsed;
                }
                else
                {
                    m_operatePanel.Visibility = System.Windows.Visibility.Visible;
                    _ctlListOperate.ItemsSource = e.Result.Data;
                    _ctlListOperate.SelectedIndex = 0;
                }
            }
            m_busy.IsBusy = false;
        }

        private void _ctlBtnDelete_Click(object sender, RoutedEventArgs e)
        {

        }

        private void _ctlBtnCancel_Click(object sender, RoutedEventArgs e)
        {
            if (_hasModified)
            {
                this.Submit();
            }
            else
            {
                this.Cancel();
            }
        }

        private void ResetToolbar(ViewMetadata viewMetadata, DataInstance dataInstance)
        {
            if (_viewMetadata.CanModify)
            {
                _ctlBtnSave.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                _ctlBtnSave.Visibility = System.Windows.Visibility.Collapsed;
            }

            if (_viewMetadata.CanRemove)
            {
                _ctlBtnDelete.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                _ctlBtnDelete.Visibility = System.Windows.Visibility.Collapsed;
            }

            if (dataInstance.Id == Guid.Empty)
            {
                m_operatePanel.Visibility = System.Windows.Visibility.Collapsed;
                _ctlBtnDelete.Visibility = System.Windows.Visibility.Collapsed;
            }
            else
            {
                m_operatePanel.Visibility = System.Windows.Visibility.Visible;
                _ctlBtnDelete.Visibility = System.Windows.Visibility.Visible;
            }
        }
    }
}
